const mysql = require("mysql");
const assert = require("assert");

const db = mysql.createPool({
  host: "",
  // user: 'root',
  // password: 'Ztxt@1234',
  user: "root",
  password: "123456",
  database: "mall", // 数据库名称
});

function filter(val) {
  return val.replace(/"/g, '\\"').replace(/'/g, "\\'");
}

db._query = db.query;

db.query = function (sql) {
  console.log("sql", sql);
  return new Promise((resolve, reject) => {
    db._query(sql, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

db.select = function (table, fields, data) {
  let WHERE = "";
  if (!data) {
    WHERE = "1 = 1";
  } else {
    WHERE = data;
  }
  return db.query(`SELECT ${fields} FROM ${table} WHERE ${WHERE}`);
};

db.insert = function (table, data) {
  let keys = [];
  let vals = [];
  for (let key in data) {
    keys.push(key);
    vals.push('"' + filter(data[key].toString()) + '"');
  }
  return db.query(
    `INSERT INTO ${table} (${keys.join(",")}) VALUES(${vals.join(",")})`
  );
};

db.update = function (table, data, where) {
  assert(where);
  assert(typeof where == "object");

  let arr = [];
  for (let i in data) {
    arr.push(`${i}="${data[i]}"`);
  }

  let whereArr = [];
  for (let i in where) {
    whereArr.push(`${i}="${where[i]}"`);
  }

  return db.query(
    `UPDATE ${table} SET ${arr.join(",")} WHERE ${whereArr.join(" AND ")}`
  );
};

db.delete = function (table, data) {
  assert(data);
  assert(typeof data == "object");

  let arr = [];
  for (let i in data) {
    arr.push(`${i}="${data[i]}"`);
  }
  return db.query(`DELETE FROM ${table} WHERE ${arr.join(" AND ")}`);
};

module.exports = db;
